import { exec } from 'child_process';
import crypto from 'crypto';
import { beautifyFormatsInfo, findVideoNameFromStdout, findVideoSizeFromStdout } from './utils';

// list all audio and video formats
export function getFormatsInfo(video_link: string) {
    return new Promise((resolve, reject) => {
        exec(`youtube-dl --list-formats ${video_link}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve(beautifyFormatsInfo(stdout, video_link));
        })
    })
}


// get the title of the video
export function getVideoTitle(video_link: string) {
    return new Promise((resolve, reject) => {
        exec(`youtube-dl --no-playlist -e ${video_link}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve(stdout.substr(0, stdout.length - 1));
        })
    })
}


// get the thumbnail url of the video and download it, return the filename.
export function getThumbnail(video_link: string) {
    return new Promise((resolve, reject) => {
        exec(`youtube-dl --no-playlist --get-thumbnail ${video_link}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            if (stdout) {
                let thumbnailUrl = stdout.substr(0, stdout.length - 1);
                let imgHashName = crypto.createHmac('sha256', thumbnailUrl).update('i love nodejs').digest('hex').substr(2, 10) + '.jpg';
                exec(`cd /root/imgs && wget -c ${thumbnailUrl} -O ${imgHashName}`);
                resolve(imgHashName);
            }
        })
    })
}


// get the vide description
export function getVideoDescription(video_link: string) {
    return new Promise((resolve, reject) => {
        exec(`youtube-dl --no-playlist --get-description ${video_link}`, (error, stdout, stderr) => {
            if (error) reject(error);
            if (stderr) reject(stderr);
            resolve(stdout.substr(0, stdout.length - 1));
        })
    })
}


// get the video's title, thumbnail's hashname and description in an async function
export async function getVideoInfo(video_link: string) {
    let [title, thumbnail, description] = await Promise.all(
        [
            getVideoTitle(video_link),
            getThumbnail(video_link),
            getVideoDescription(video_link)
        ]
    );

    return JSON.stringify({
        title,
        thumbnail,
        description
    })
}
